import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  List, 
  Avatar, 
  Tag, 
  Button, 
  Input, 
  Select, 
  Space, 
  Pagination,
  Empty,
  Spin,
  Tabs,
  Image,
  Row,
  Col
} from 'antd';
import { 
  ShareAltOutlined, 
  PlusOutlined, 
  SearchOutlined,
  EyeOutlined,
  LikeOutlined,
  CommentOutlined,
  ClockCircleOutlined,
  DownloadOutlined,
  PictureOutlined
} from '@ant-design/icons';
import { Post } from '../../types';
import './Share.scss';

const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const Share: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [posts, setPosts] = useState<Post[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [sortBy, setSortBy] = useState('latest');
  const [activeTab, setActiveTab] = useState('all');

  // 模拟分享数据
  const mockPosts: Post[] = [
    {
      id: '1',
      title: 'React 学习资料合集',
      content: '整理了React从入门到进阶的完整学习资料，包括官方文档、教程视频、实战项目等',
      author: { id: '1', username: '前端导师', email: 'frontend@example.com', role: 'student' },
      category: 'share',
      tags: ['学习资料', 'React', '前端'],
      createdAt: '2024-01-15T10:30:00Z',
      updatedAt: '2024-01-15T10:30:00Z',
      likes: 89,
      comments: 34,
      views: 456,
    },
    {
      id: '2',
      title: '校园里的樱花开了',
      content: '今天路过樱花大道，发现樱花已经开了，粉色的花瓣真的很美，分享给大家看看',
      author: { id: '2', username: '摄影爱好者', email: 'photo@example.com', role: 'student' },
      category: 'share',
      tags: ['风景', '樱花', '校园'],
      createdAt: '2024-01-15T09:15:00Z',
      updatedAt: '2024-01-15T09:15:00Z',
      likes: 156,
      comments: 28,
      views: 789,
    },
    {
      id: '3',
      title: '推荐一个好用的学习APP',
      content: 'Forest专注森林，一个帮助专注学习的APP，界面简洁，功能实用，强烈推荐',
      author: { id: '3', username: '效率达人', email: 'efficiency@example.com', role: 'student' },
      category: 'share',
      tags: ['好东西', 'APP', '学习工具'],
      createdAt: '2024-01-15T08:45:00Z',
      updatedAt: '2024-01-15T08:45:00Z',
      likes: 67,
      comments: 19,
      views: 234,
    },
    {
      id: '4',
      title: 'Python 数据分析资料包',
      content: '收集了Python数据分析相关的书籍、教程、数据集，适合初学者和进阶者',
      author: { id: '4', username: '数据科学家', email: 'data@example.com', role: 'student' },
      category: 'share',
      tags: ['学习资料', 'Python', '数据分析'],
      createdAt: '2024-01-14T16:30:00Z',
      updatedAt: '2024-01-14T16:30:00Z',
      likes: 123,
      comments: 45,
      views: 567,
    },
    {
      id: '5',
      title: '校园夜景分享',
      content: '晚上的校园真的很美，图书馆的灯光，湖面的倒影，分享几张夜景照片',
      author: { id: '5', username: '夜猫子', email: 'night@example.com', role: 'student' },
      category: 'share',
      tags: ['风景', '夜景', '校园'],
      createdAt: '2024-01-14T14:20:00Z',
      updatedAt: '2024-01-14T14:20:00Z',
      likes: 78,
      comments: 23,
      views: 345,
    },
  ];

  const subCategories = [
    { key: 'all', label: '全部分享' },
    { key: 'study', label: '学习资料' },
    { key: 'good', label: '好东西' },
    { key: 'scenery', label: '风景' },
  ];

  useEffect(() => {
    loadPosts();
  }, [currentPage, searchKeyword, sortBy, activeTab]);

  const loadPosts = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filteredPosts = mockPosts;
      
      // 按子分类过滤
      if (activeTab !== 'all') {
        filteredPosts = mockPosts.filter(post => {
          const firstTag = post.tags[0];
          switch (activeTab) {
            case 'study':
              return firstTag === '学习资料' || firstTag === 'React' || firstTag === 'Python';
            case 'good':
              return firstTag === '好东西' || firstTag === 'APP' || firstTag === '学习工具';
            case 'scenery':
              return firstTag === '风景' || firstTag === '樱花' || firstTag === '夜景';
            default:
              return true;
          }
        });
      }
      
      // 按关键词搜索
      if (searchKeyword) {
        filteredPosts = filteredPosts.filter(post => 
          post.title.includes(searchKeyword) || 
          post.content.includes(searchKeyword) ||
          post.tags.some(tag => tag.includes(searchKeyword))
        );
      }
      
      // 排序
      filteredPosts.sort((a, b) => {
        switch (sortBy) {
          case 'latest':
            return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
          case 'popular':
            return b.views - a.views;
          case 'likes':
            return b.likes - a.likes;
          case 'comments':
            return b.comments - a.comments;
          default:
            return 0;
        }
      });
      
      setPosts(filteredPosts);
      setTotal(filteredPosts.length);
    } catch (error) {
      console.error('加载分享失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handlePostClick = (postId: string) => {
    navigate(`/posts/share/${postId}`);
  };

  const handleDownload = (postId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    console.log('下载资源:', postId);
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handleSortChange = (value: string) => {
    setSortBy(value);
    setCurrentPage(1);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setCurrentPage(1);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  };

  const getSubCategoryColor = (tag: string) => {
    const colors = {
      '学习资料': 'blue',
      '好东西': 'green',
      '风景': 'orange',
      'React': 'cyan',
      'Python': 'purple',
      'APP': 'magenta',
    };
    return colors[tag as keyof typeof colors] || 'default';
  };

  return (
    <div className="share-page">
      <div className="page-header">
        <div className="header-left">
          <h1>分享区</h1>
          <p>分享资源，分享美好，分享生活</p>
        </div>
      </div>

      {/* 子分类标签 */}
      <Card className="category-card">
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          items={subCategories.map(cat => ({
            key: cat.key,
            label: cat.label,
          }))}
        />
      </Card>

      {/* 筛选和搜索 */}
      <Card className="filter-card">
        <div className="filter-content">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索分享内容..."
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Select
              value={sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
            >
              <Option value="latest">最新发布</Option>
              <Option value="popular">最多浏览</Option>
              <Option value="likes">最多点赞</Option>
              <Option value="comments">最多评论</Option>
            </Select>
          </Space>
        </div>
      </Card>

      {/* 分享列表 */}
      <Card className="posts-card">
        <Spin spinning={loading}>
          {posts.length > 0 ? (
            <List
              dataSource={posts}
              renderItem={(post) => (
                <List.Item
                  className="post-item"
                  onClick={() => handlePostClick(post.id)}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={<ShareAltOutlined />} />}
                    title={
                      <div className="post-title">
                        <span>{post.title}</span>
                        <Tag color={getSubCategoryColor(post.tags[0])}>
                          {post.tags[0]}
                        </Tag>
                      </div>
                    }
                    description={
                      <div className="post-content">
                        <div className="post-preview">
                          <div className="post-text">
                            <p>{post.content}</p>
                          </div>
                          <div className="post-image">
                            <Image
                              src="https://picsum.photos/120/80?random=1"
                              alt="分享图片"
                              width={120}
                              height={80}
                              style={{ borderRadius: 6 }}
                            />
                          </div>
                        </div>
                        
                        <div className="post-tags">
                          {post.tags.map((tag, index) => (
                            <Tag key={index} size="small" color={getSubCategoryColor(tag)}>
                              {tag}
                            </Tag>
                          ))}
                        </div>
                        
                        <div className="post-meta">
                          <div className="post-author">
                            <span>作者：{post.author.username}</span>
                            <span className="post-time">
                              <ClockCircleOutlined /> {formatDate(post.createdAt)}
                            </span>
                          </div>
                          <div className="post-stats">
                            <span><EyeOutlined /> {post.views}</span>
                            <span><LikeOutlined /> {post.likes}</span>
                            <span><CommentOutlined /> {post.comments}</span>
                            <Button 
                              type="text" 
                              size="small"
                              icon={<DownloadOutlined />}
                              onClick={(e) => handleDownload(post.id, e)}
                            >
                              下载
                            </Button>
                          </div>
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Empty 
              description="暂无分享内容"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Spin>
        
        {total > 0 && (
          <div className="pagination-wrapper">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={10}
              onChange={setCurrentPage}
              showSizeChanger={false}
              showTotal={(total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </Card>
    </div>
  );
};

export default Share;
